<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class ApiResponseMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        $response = $next($request);

        // 只处理API路由的JSON响应
        if ($request->is('api/*') && $response instanceof JsonResponse) {
            $originalData = $response->getData(true);
            $statusCode = $response->getStatusCode();

            // 如果已经是标准格式，直接返回
            if (isset($originalData['success']) && isset($originalData['code']) && isset($originalData['message'])) {
                return $response;
            }

            // 统一响应格式
            $formattedResponse = [
                'success' => $statusCode >= 200 && $statusCode < 300,
                'code' => $statusCode,
                'message' => $this->getStatusMessage($statusCode),
                'data' => $originalData,
                'timestamp' => now()->toISOString(),
                'request_id' => $request->header('X-Request-ID', uniqid()),
            ];

            // 添加错误信息
            if ($statusCode >= 400) {
                $formattedResponse['message'] = $originalData['message'] ?? $this->getStatusMessage($statusCode);
                $formattedResponse['errors'] = $originalData['errors'] ?? null;
            }

            $response->setData($formattedResponse);
        }

        return $response;
    }

    /**
     * 获取状态码对应的消息
     */
    private function getStatusMessage(int $statusCode): string
    {
        return match ($statusCode) {
            200 => '请求成功',
            201 => '创建成功',
            204 => '删除成功',
            400 => '请求参数错误',
            401 => '未授权访问',
            403 => '权限不足',
            404 => '资源不存在',
            405 => '方法不允许',
            422 => '数据验证失败',
            429 => '请求过于频繁',
            500 => '服务器内部错误',
            503 => '服务不可用',
            default => '未知状态',
        };
    }
}